package cn.wolfcode.luowowo.website.resolver;

import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annotion.UserParam;
import cn.wolfcode.luowowo.website.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//自定义参数解析器
public class UserInfoArgumentResolver implements HandlerMethodArgumentResolver {

    @Reference
    private IUserInfoRedisService userInfoRedisService;

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.hasParameterAnnotation(UserParam.class)
                &&methodParameter.getParameterType() == UserInfo.class;
        //UserParam这个自定义注解用于区分自定义参数解析器与springmvc自带的参数解析器
    }
    //如果上面的supportsParamenter返回true,表示需要执行参数解析逻辑
    @Override
    public Object resolveArgument(MethodParameter methodParameter,
                                  ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest,
                                  WebDataBinderFactory webDataBinderFactory) throws Exception {
       //获取当前登录用户对象,并返回,springmvc 会帮您自动参数对象
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        HttpServletResponse response = nativeWebRequest.getNativeResponse(HttpServletResponse.class);
        String token = CookieUtil.getToken(request, response);
        UserInfo userByToken = userInfoRedisService.getUserByToken(token);
//        if(cookie != null){
//            return userInfoRedisService.getUserInfoByToken(cookie.getValue());
//        }
        return userByToken;
    }
}
